<template>
  <div class="p-3 w-full">
    <div class="flex justify-between mb-2">
      <div>
        <el-button class="button_normal" type="primary" @click="addOpenForm"
          >添加</el-button
        >
      </div>
      <div class="flex">
        <el-input
          type="text"
          v-model="searchValue"
          style="width: 300px"
          clearable
          @change="loadTable({ username: searchValue })"
          placeholder="请输入用户名"
          :prefix-icon="Search"
        >
        </el-input>
        <!-- <el-button
          @click="loadTable({ name: searchValue })"
          type="primary"
          size="large"
          >搜索</el-button
        > -->
      </div>
    </div>
    <el-table :data="list" width="100%" v-loading="loading">
      <el-table-column
        prop="id"
        sortable
        label="编号"
        width="100px"
        align="center"
      />
      <el-table-column prop="username" label="用户名" align="center" />
      <el-table-column label="头像" width="80px" align="center">
        <template #default="scope">
          <!-- <el-image
            :src="'http://localhost:8181/' + scope.row.avatar"
            :zoom-rate="1.2"
            :preview-src-list="['http://localhost:8181/' + scope.row.avatar]"
            fit="cover"
          /> -->
          <el-avatar :src="'http://localhost:8181/' + scope.row.avatar" />
        </template>
      </el-table-column>
      <el-table-column
        prop="password"
        label="密码"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="email"
        label="邮箱"
        align="center"
      ></el-table-column>
      <el-table-column prop="sex" label="性别" align="center">
        <template #default="scope">
          {{ scope.row.sex == 0 ? "女" : "男" }}
        </template>
      </el-table-column>
      <el-table-column
        prop="location"
        label="地址"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="introduction"
        label="简介"
        align="center"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column fixed="right" label="操作" width="300px" align="center">
        <template #default="scope">
          <el-button
            size="small"
            @click="updateOpenForm(scope.row)"
            class="button_normal"
            >编辑</el-button
          >
          <el-popconfirm
            @confirm="deleteData(scope.row.username)"
            title="确定删除？"
          >
            <template #reference>
              <el-button size="small" class="button_delete">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      small
      background
      layout="prev, pager, next"
      :total="total"
      class="mt-4"
      v-model:current-page="pageNum"
      v-model:page-size="pageSize"
      @current-change="currentChange"
    />
    <el-dialog
      v-model="dialogVisible"
      :title="!isUpdate ? '添加' : '编辑'"
      @close="resetForm(formRef)"
      width="30%"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        size="default"
        status-icon
      >
        <el-form-item label="昵称" prop="name">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="账号" prop="username">
          <el-input v-model="form.username" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password" type="password" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" />
        </el-form-item>
        <el-form-item label="地址" prop="location">
          <el-input v-model="form.location" />
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-radio-group v-model="form.sex" class="ml-4">
            <el-radio :label="1">男</el-radio>
            <el-radio :label="0">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="简介" prop="introduction">
          <el-input type="textarea" v-model="form.introduction" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="isUpdate ? update(formRef) : add(formRef)"
          >
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import { ref, onMounted } from "vue";
import request from "@/api/http";
import { useRouter, useRoute } from "vue-router";
import { Search } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
const router = useRouter();
const route = useRoute();
const loading = ref(false);
const list = ref([]);
const pageNum = ref(1);
const pageSize = ref(8);
const total = ref(0);
const searchValue = ref("");
const isUpdate = ref(false);
const formRef = ref(null);
const form = ref({
  username: "",
  name: "",
  password: "",
  email: "",
  introduction: "",
  phone: "",
  sex: "",
  location: "",
});
const initForm = {
  username: "",
  name: "",
  password: "",
  email: "",
  introduction: "",
  phone: "",
  sex: "",
  location: "",
};
const rules = ref({
  username: [
    {
      required: true,
      message: "请输入账号",
      trigger: "blur",
    },
  ],
  password: [
    {
      required: true,
      message: "请输入密码",
      trigger: "blur",
    },
  ],
  email: [
    {
      type: "email",
      message: "请输入邮箱格式",
      trigger: ["blur"],
    },
  ],
});
onMounted(() => {
  loadTable();
});
const loadTable = (
  data = {
    // type: "玄幻",
    // "author":"唐家三少",
    // name: value,
  }
) => {
  if (searchValue.value == "") {
    data = {};
  }
  loading.value = true;
  request({
    url: "/user/loadpage",
    method: "post",
    data: {
      pageNum: pageNum.value,
      pageSize: pageSize.value,
      data: data,
    },
  }).then((res) => {
    // console.log(res);
    if (res.code == 200) {
      list.value = res.data.records;
      total.value = res.data.total;
      loading.value = false;
    }
  });
};
const currentChange = (value) => {
  loadTable();
};
const dialogVisible = ref(false);
const deleteData = (username) => {
  request.delete("user/" + username).then((res) => {
    if (res.code == 200) {
      ElMessage.success("删除成功！");
      loadTable();
    } else {
      ElMessage.error("系统错误！");
    }
  });
};
const add = async (formEl) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      request({
        url: "user/insert",
        method: "post",
        data: form.value,
      }).then((res) => {
        if (res.code == 200) {
          ElMessage.success("添加成功！");
          dialogVisible.value = false;
          loadTable();
        } else if (res.code == 400) {
          ElMessage.info("账号已经存在");
        } else {
          ElMessage.error("添加失败");
        }
      });
    }
  });
};
const update = async (formEl) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      request({
        url: "user/edituser",
        method: "post",
        data: form.value,
      }).then((res) => {
        if (res.code == 200) {
          ElMessage.success("编辑成功！");
          dialogVisible.value = false;
          loadTable();
        } else {
          ElMessage.error("编辑失败");
        }
      });
    }
  });
};
const addOpenForm = () => {
  form.value = initForm;
  isUpdate.value = false;
  dialogVisible.value = true;
};
const updateOpenForm = (row) => {
  form.value = { ...row };
  isUpdate.value = true;
  dialogVisible.value = true;
};
const fileOnChange = (data) => {
  form.value.cover = data.raw;
};
const resetForm = (formEl) => {
  if (!formEl) return;
  formEl.resetFields();
};
</script>
<style scoped>
.avatar-uploader .avatar {
  width: 100px;
  height: 100px;
  display: block;
}
</style>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  text-align: center;
}
</style>
